class Solution(object):
    def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes):
        n = len(status)
        available = {index for index in range(n) if status[index]}
        ans = 0
        st = set(initialBoxes)
        flag = True
        while flag:
            flag = False
            next_st = set()
            for box in st:
                if box in available:
                    flag = True
                    if keys[box]:
                        available.update(set(keys[box]))
                    if containedBoxes[box]:
                        next_st.update(set(containedBoxes[box]))
                    ans += candies[box]
                else:
                    next_st.add(box)
            st = next_st
        return ans
